package com.zx.idc.backend.gui.api.commom.factory;

import com.zx.idc.common.spring.SpringBeanUtil;
import com.zx.idc.common.spring.SpringConfigUtil;
import com.zx.idc.ds.sys.service.ISysConfigurationService;
import com.zx.idc.xml.entity.FileLoad;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.zx.idc.common.attributes.InterfaceParamConfiguration.*;
import static com.zx.idc.common.attributes.SystemAttributes.WEB_SERVICE_VERSION;

/**
 * ftp上报数据工厂@{FileLoad}
 */
public class FtpUploadDataFactory {

    private static final Logger LOG = LoggerFactory.getLogger(FtpUploadDataFactory.class);

    /**
     * 获取加密上报数据实体
     *
     * @return
     */
    public static FileLoad getFtpUploadFileLoadEntity(String srcXmlData, String idcId) {
        try {
            //2.压缩
            String encryptionKey = getVal(ENCRYPTION_KEY);
            String authenticationKey = getVal(AUTHENTICATION_KEY);
            Integer enCmpType = Integer.valueOf(getVal(COMPRESSION_FORMAT));
            byte[] enCmpBytes = CompressionProvider.enCMP(enCmpType, srcXmlData);
            //3.hash
            Integer hashType = Integer.valueOf(getVal(HASH_ALGORITHM));
            String dataHash = HashProvider.hashByBase64(hashType, enCmpBytes, authenticationKey);
            //4.加密
            Integer encryptType = Integer.valueOf(getVal(ENCRYPTION_ALGORITHM));
            String dataUpload = EncryptProvider.encrypt(encryptType, enCmpBytes, encryptionKey, getVal(ASE_OFFSET));
            return new FileLoad()
                .setCommandVersion(getConfig(WEB_SERVICE_VERSION))
                .setCompressionFormat(enCmpType)
                .setEncryptAlgorithm(encryptType)
                .setHashAlgorithm(hashType)
                .setIdcId(idcId)
                .setDataHash(dataHash)
                .setDataUpload(dataUpload);
        } catch (Exception e) {
            LOG.error("get fileLoad bean : obtain encrypted report entity exception is failed", e);
        }
        return null;
    }

    /**
     * 获取值 先从后台获取值，没有则从配置文件获取
     *
     * @param key
     * @return
     */
    private static String getVal(String key) {
        ISysConfigurationService iSysConfigurationService = SpringBeanUtil.getBean(ISysConfigurationService.class);
        return iSysConfigurationService.getVal(key);
    }

    /**
     * 获取配置文件值
     *
     * @param key
     * @return
     */
    private static String getConfig(String key) {
        return SpringConfigUtil.get(key);
    }
}
